package main
import (
	"fmt"
	"github.com/BurntSushi/toml"
        "io"
	"mime/multipart"
        "io/ioutil"
	"os"
	"os/exec"
        "log"
	"strings"
	"net/http"
	"time"
	"bytes"
)
type Info struct {
        Fdir           string
        HttpUrl        string
}
var configData Info=Info{}
var httpLog *log.Logger
func ReadConf() bool {
        fp, err := os.Open("./conf.toml")
        if err != nil {
                fmt.Printf("open  error\n")
                return false
        }
        fcontent, err := ioutil.ReadAll(fp)
        if err != nil {
                fmt.Printf("ReadAll error\n")
                return false
        }
        err = toml.Unmarshal(fcontent, &configData)
        if err != nil {
                fmt.Printf("Unmarshal error\n")
                return false
        }
        return true
}
func postFile(filename string, buf *bytes.Buffer) error {
	httpLog.Printf("Begin to postFile for %s.",filename)
	buf.Reset()
	bodyWriter:=multipart.NewWriter(buf)
	fileWriter,err:=bodyWriter.CreateFormFile("uploadfile",filename)
	if err!=nil {
		httpLog.Println("error writing to buffer")
		return err
	}
	fh,err:=os.Open(filename)
	if err!=nil {
		httpLog.Println("error opening file")
		return err
	}
	_,err=io.Copy(fileWriter,fh)
	if err!=nil {
		return err
	}
	contentType:=bodyWriter.FormDataContentType()
	bodyWriter.Close()
	resp,err:=http.Post(configData.HttpUrl,contentType,buf)
	if err!=nil  {
		httpLog.Printf("error post content to http server!\n")
		return err
	}
	defer resp.Body.Close()
	resp_body,err:=ioutil.ReadAll(resp.Body)
	if err!=nil {
		return err
	}
	httpLog.Printf(string(resp_body))
	httpLog.Printf("End to postFile for %s.",filename)
	return nil
}
func main(){
	result:=ReadConf()
	if result!=true {
		fmt.Printf("Read configdata error!\n")
		return
	}
        logFile, err := os.Create("./l.log")
        defer logFile.Close()
        if err != nil {
                fmt.Printf("Open file error!\n")
        }
	httpLog= log.New(logFile, "[Info]", log.Ldate|log.Ltime|log.Lshortfile)
	buf:=new(bytes.Buffer)
	timer1:=time.NewTicker(time.Duration(100)*time.Millisecond)
	bsh := fmt.Sprintf("md5sum %s/index.m3u8",configData.Fdir)
        cmd := exec.Command("/bin/bash", "-c", bsh)
        cmd.Stdout = buf
	err=cmd.Run()
	if err!=nil {
		httpLog.Println(err)
		return
	}
	var md1,md2 string
	buft:=new(bytes.Buffer)
	md1=buf.String()
	var len1,len2 =0,0
	for {
		select {
		case<-timer1.C:
			buf.Reset()
			bsh := fmt.Sprintf("md5sum %s/index.m3u8",configData.Fdir)
		        cmd := exec.Command("/bin/bash", "-c", bsh)
        		cmd.Stdout = buf
        		err:=cmd.Run()
        		if err!=nil {
               			 httpLog.Println(err)
               			 return
       			}
        		md2=buf.String()
			if md1!=md2 {
				md1=md2
				err:=postFile(configData.Fdir+"/index.m3u8",buft)
				if err!=nil {
					httpLog.Printf("error postFile index.m3u8!\n")
					break
				}
				da,err:=ioutil.ReadFile(configData.Fdir+"/index.m3u8")
				if err!=nil {
					httpLog.Printf("error readfile!\n")
					break
				}
				dat:=string(da)
				len2=len(dat)
				if len2<=len1 {
					httpLog.Printf("not a updated index.m3u8!\n")
					break
				}
				data:=string(dat[len1:len2])
				len1=len2
				var length int
				for {
					pos:=strings.Index(data,".ts")
               				if pos==-1 {
						httpLog.Printf("Not found ts files in %s.",data)
                     				break
               				}
					length=len(data)
					if pos-21<0 {
						httpLog.Printf("Not a right pos!\n")
						break
					}
                			httpLog.Printf(string(data[(pos-21):(pos+3)]))
					err:=postFile(configData.Fdir+"/"+string(data[(pos-21):(pos+3)]),buft)
					if err!=nil {
						httpLog.Printf("error postFile for %s.\n",string(data[(pos-21):(pos+3)]))
					}
					err=os.Remove(configData.Fdir+"/"+string(data[(pos-21):(pos+3)]))
					if err!=nil {
						httpLog.Println(err)
					}
              				data=string(data[(pos+3):length])
        			}
			}
		}
	}
}
							
					

















								
				
	
